<?php
namespace app\services\ai;

use app\services\ai\traits\HasHttpRequest;
use app\services\ai\traits\qq\BaseText;
use app\services\ai\traits\qq\ComputerVisionOcr;
use app\services\ai\traits\qq\EffectImage;
use app\services\ai\traits\qq\NaturalLanguage;
use app\services\ai\traits\qq\Translate;
use app\services\ai\traits\qq\VoiceMerge;

class Qq implements AiInterface
{
    use HasHttpRequest,
        ComputerVisionOcr,
        EffectImage,
        NaturalLanguage,
        Translate,
        BaseText,
        VoiceMerge;

    const
        API_END_POINT = 'https://api.ai.qq.com/fcgi-bin/',
        //OCR
        API_ID_CARD_OCR = 'ocr/ocr_idcardocr',
        OCR_ID_CARD_TYPE_FRONT = 0,   //id card 正面
        OCR_ID_CARD_TYPE_BACK = 1,   //id card 背面
        API_GENERAL_OCR = 'ocr/ocr_generalocr',
        API_IMAGE_TAG = 'image/image_tag',

        //基本文本分析
        API_NLP_WORDSEG = 'nlp/nlp_wordseg', //分词
        API_NLP_WORDPOS = 'nlp/nlp_wordpos', //词性标注
        API_NLP_WORDNER = 'nlp/nlp_wordner', //专有名词识别
        API_NLP_WORDSYN = 'nlp/nlp_wordsyn', //同义词识别

        //机器翻译
        API_NLP_TEXT_TRANS = 'nlp/nlp_texttrans',
        API_NLP_TEXT_TRANSLATE = 'nlp/nlp_texttranslate',
        API_NLP_IMAGE_TRANSLATE = 'nlp/nlp_imagetranslate',

        //智能闲聊
        API_NLP_TEXTCHAT = 'nlp/nlp_textchat',
        //语音合成
        AAI_TTS_FORMAT_PCM = 1,
        AAI_TTS_FORMAT_WAV = 2,
        AAI_TTS_FORMAT_MP3 = 3,
        API_AAI_TTS = 'aai/aai_tts', //AI LAB
        API_AAI_TTA = 'aai/aai_tta', //youtu
        API_AAI_ASR = 'aai/aai_asr', //语音识别-echo版
        API_AAI_ASRS = 'aai/aai_asrs', //语音识别-AI LAB版
        API_AAI_WXARS = 'aai/aai_wxasrs', //语音识别 WECHAT AI版
        //图像
        API_EFFECT_FACE_MERGE = 'ptu/ptu_facemerge',
        API_EFFECT_FACE_STICKER = 'ptu/ptu_facesticker';

    public static $aaiTtsExt = [1 => 'pcm', 2 => 'wav', 3 => 'mp3'];




    protected $timeout = 60.0;

    protected $config;

    public function __construct($config)
    {
        $this->config = $config;
    }

    public function getBaseUri()
    {
        return self::API_END_POINT;
    }

    public function sign($params)
    {
        $base = [
            'app_id' => $this->config['app_id'] ?? '',
            'time_stamp' => time(),
            'nonce_str' => str_random(10),
        ];
        $signArr = array_merge($base, $params);
        ksort($signArr, SORT_STRING);
        $signArr['app_key'] = $this->config['app_key'] ?? '';
        $str1 = http_build_query($signArr);
        unset($signArr['app_key']);
        $signArr['sign'] = strtoupper(md5($str1));
        return $signArr;
    }

    public function parseOptions($params)
    {
        return [
            'form_params' => $this->sign($params),
            'headers' => ['Host' => 'api.ai.qq.com']
        ];
    }
}
